using CanvasUI;
using System.Collections.Generic;
using KissEcs;
using UnityEngine;

namespace Rotary
{
    public class RotaryMgr : NormalSingleton<Rotary.RotaryMgr>
    {
        public List<RotaryCell> rotaryCellList = new();
        public int startIdx;
        public int num;//抽取次数(单抽，三联抽，五连抽)

        public RotaryType currType = RotaryType.Skill;
        //public LotteryType lotteryType = LotteryType.Single;

        public void LoadStartEvent()
        {
            EventManager.Register("RewardSkill", this, AddRotaryEvent);
        }

        private void ComputeReawrdType()
        {
            //抽取主要奖励
            GetRewardSkill();
        }

        /// <summary>
        /// 抽取列表(示例)
        /// </summary>
        public void GetRewardSkill()
        {
            UIManager.Instance.GetUI<BattleUI>(UI.Battle).isWaiting = true;
            if (rotaryCellList.Count != 0)
            {
                rotaryCellList.Clear();
            }

            List<int> skillList = new();
            Dictionary<int, int> dict = new();
            List<int> skillPool = GetSkillPool();
            int remainSkillCount = 0;
            foreach (var item in skillPool)
            {
                int remain = ReaminSkillCount(item);
                dict.Add(item, remain);
                remainSkillCount += remain;
            }
            if(remainSkillCount == 0)
            {
                Debug.Log("所有奖励已获取，无法进行转盘奖励抽取");
                return;
            }

            int needLevel = World.GetModel<cfg.Tables>().TbCopy.Get(Global.GetMapTableId(Global.Player.AvatarOther.GameDifficultyType == GameDifficulty.Easy))
                .SkillBox.Level;

            num = GetSkillCount(1, Global.Player.AvatarOther.level >= needLevel ? 302 : 301);
            if (remainSkillCount < num)
            {
                if (remainSkillCount < 3)
                {
                    num = 1;
                }
                else if (remainSkillCount < 5)
                {
                    num = 3;
                }
            }

            for (int i = 0; i < num; i++)
            {
                int id = RandomGetSkill(skillPool);
                skillList.Add(id);
                World.GetSystem<PlayerSkillSystem>().UpgradeSkill(id);//升级技能
                dict[id]--;
                if (dict[id] == 0)
                {
                    skillPool.Remove(id);
                }
            }

            RandomChosenRewardPos(skillList);
        }

        /// <summary>
        /// 获取抽取技能数
        /// </summary>
        /// <param name="num"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public int GetSkillCount(int num, int id)
        {
            List<int> list = new();
            var table = World.GetModel<cfg.Tables>().TbShopBoxOutput.Get(id);
            int white = 0;
            int green = 0;
            int purple = 0;
            int count = 0;

            foreach (var item in table.Qutput)
            {
                if (item.Quality == cfg.equip.Quality.WHITE)
                {
                    white += item.Weight;
                }
                if (item.Quality == cfg.equip.Quality.GREEN)
                {
                    green += item.Weight;
                }
                if (item.Quality == cfg.equip.Quality.PURPLE)
                {
                    purple += item.Weight;
                }
                count += item.Weight;
            }

            int chosen = 0;

            for (int i = 0; i < num; i++)
            {
                int power = Random.Range(0, count);
                if (power < white)
                {
                    list.Add(1);
                }
                else if (power < white + green)
                {
                    list.Add(3);
                }
                else
                {
                    list.Add(5);
                }
            }

            foreach (int k in list)
            {
                if (k > chosen)
                {
                    chosen = k;
                }
            }

            return chosen;
        }

        /// <summary>
        /// 获取奖励池
        /// </summary>
        /// <returns></returns>
        public List<int> GetSkillPool()
        {
            List<int> skillPool = new();
            var table = World.GetModel<cfg.Tables>().TbSkills;
            var skillList = World.GetModel<GamingData>().skillList;
            foreach (var item in skillList)
            {
                skillPool.Add(item.skillID);
                if (table.Get(item.skillID).Type == cfg.skill.type.PASSIVITY && item.skillLevel == 5)
                {
                    skillPool.Remove(item.skillID);
                }
                if (table.Get(item.skillID).Type != cfg.skill.type.PASSIVITY)
                {
                    if (item.skillLevel == 6)
                    {
                        skillPool.Remove(item.skillID);
                    }
                    if (item.skillLevel == 5 && !item.canEvolution)
                    {
                        skillPool.Remove(item.skillID);
                    }
                }
            }

            return skillPool;
        }

        /// <summary>
        /// 技能剩余次数
        /// </summary>
        /// <returns></returns>
        public int ReaminSkillCount(int id)
        {
            int num = 0;
            //奖励逻辑
            return num;
        }

        public int RandomGetSkill(List<int> skillPool)
        {
            return skillPool[Random.Range(0, skillPool.Count)];
        }

        /// <summary>
        /// 随机奖励位置
        /// </summary>
        /// <param name="lists"></param>
        private void RandomChosenRewardPos(List<int> lists)
        {
            //List<int> idList = new() { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };

            startIdx = Random.Range(0, 12);
            Debug.Log($"startIdx:{startIdx}");
            for (int i = 0; i < lists.Count; i++)
            {
                int idx = startIdx - i;
                if (idx < 0)
                {
                    idx += 12;
                }
                RotaryCell obj = new() { idx = idx, skillId = lists[i] };
                //Debug.Log($"obj.idx:{obj.idx},obj.skillid:{obj.skillId}");
                rotaryCellList.Add(obj);
            }

            //填充其他格子
            FillOtherIcon();
        }

        private void FillOtherIcon()
        {
            //获取其他奖励，填充至格子中
            var skillPool = GetSkillPool();
            List<int> lists = new();
            foreach (RotaryCell cell in rotaryCellList)
            {
                lists.Add(cell.skillId);
            }

            for (int i = 0; i < 12; i++)
            {
                bool trueSkill = false;
                foreach (RotaryCell cell in rotaryCellList)
                {
                    if (cell.idx == i)
                    {
                        trueSkill = true;
                    }
                }

                if (!trueSkill)
                {
                    RotaryCell cell = new() { idx = i, skillId = RandomGetSkill(skillPool) };
                    rotaryCellList.Add(cell);
                }
            }

            //启动转盘RotaryTable
            UIManager.Instance.Show(UI.RotaryTable).Run(() =>
            {
                var script = UIManager.Instance.GetUI<RotaryTable>(UI.RotaryTable);
                script.chosenIdx = startIdx;
                script.upgradeSkillList = lists;
                script.idxCount = num;
                script.FillIcon(rotaryCellList);
            }).Done();
        }
    }

    public enum RotaryType
    {
        Skill,
        Gold,
    }

    //public enum LotteryType
    //{
    //    Single,//单抽
    //    Trible,//三联抽
    //    Quintuple,//五连抽
    //}

    public class RotaryCell
    {
        public int idx;
        public int skillId;
    }
}

